package cn.fengshenghospital.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import cn.fengshenghospital.shiro.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /**
     * 方法执行顺序
     * getRealm ---> getDefaultWebSecurtyManager ---> getShiroFilterFactoryBean
     */

    //Spring容器启动将安全管理器注入并拦截请求路径
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        filterFactoryBean.setSecurityManager(securityManager);
        /**
         *  添加Shiro内置过滤器  实现权限拦截
         *  anon：无需认证即可访问
         *  authc：必须认证才可以访问
         *  user：使用rememberMe的功能可以直接访问
         *  perms：授权资源权限才可以访问
         *  role：指定角色才可以访问
         */
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/menu/queryMenu","authc");
        filterMap.put("/cmsMenu","authc");
        //授权拦截  只用授权才能进行操作
        filterMap.put("/menu/queryMenu","perms[menu:queryMenu]");
        //修改跳转的登录页面 默认是login.jsp
        filterFactoryBean.setLoginUrl("login.html");
        filterFactoryBean.setFilterChainDefinitionMap(filterMap);



        return filterFactoryBean;
    }

    //DefaultWebSecurityManager将自定义的Realm自动注入
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联Realm
        securityManager.setRealm(realm);
        return securityManager;
    }

    //将Realm添加到Spring
    @Bean
    public Realm getRealm(){
        return new Realm();
    }

    //thymeleaf和shiro配合使用
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
